//
//  RQActionSheet.m
//  RQActionSheet
//
//  Created by RocQ on 2017/6/5.
//  Copyright © 2017年 fengchao. All rights reserved.
//

#import "RQActionSheet.h"
#import "RQActionSheetCell.h"

#define kScreenWidth   ([UIScreen mainScreen].bounds.size.width)
#define kScreenHeight  ([UIScreen mainScreen].bounds.size.height)

static NSString * const kRQActionSheetCellIdentifier = @"kRQActionSheetCellIdentifier";
CGFloat const RQSActionSheetSectionHeight = 10; ///< 分区间距
CGFloat const RQSActionSheetLeftRightMargin = 12; ///<左右间距

@interface RQActionSheet()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, copy) NSArray<NSString *> *items;
@property (nonatomic, copy) RQActionSheetHandler selectedHandler;
@property (nonatomic, copy) RQActionSheetMultipleHandler multiplesDelectedHandler;

@property (nonatomic, weak) UIView *controllerView;
@property (nonatomic, weak) UIButton *cover;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *bottomBtn;

@property (nonatomic, strong) NSMutableArray *selectArray;


@end
@implementation RQActionSheet

- (NSMutableArray *)selectArray {
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

- (UITableView *)tableView {
    
    if (_tableView) return _tableView;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    _tableView.scrollEnabled = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.bounces = NO;
    _tableView.layer.cornerRadius = 5;
    
    [_tableView registerClass:[RQActionSheetCell class] forCellReuseIdentifier:kRQActionSheetCellIdentifier];
    
    return _tableView;
}

- (UIButton *)bottomBtn
{
    if (_bottomBtn) return _bottomBtn;

    _bottomBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _bottomBtn.tintColor = [UIColor blackColor];
    NSString *title = self.isMultiple ? @"确定" : @"取消";
    [_bottomBtn setTitle:title forState:UIControlStateNormal];
    _bottomBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_bottomBtn addTarget:self action:@selector(clickBottomBtn) forControlEvents:UIControlEventTouchUpInside];
    _bottomBtn.backgroundColor = [UIColor whiteColor];
    _bottomBtn.layer.cornerRadius = 5;

    return _bottomBtn;
}

- (UIView *)controllerView
{
    if (_controllerView) return _controllerView ;

    UIView *controllerView = [[UIView alloc]init];
    
    [self addSubview:controllerView];
    
    _controllerView = controllerView;

    return _controllerView;
}

- (UIButton *)cover
{
    if (_cover ) return _cover;
    UIButton *cover = [[UIButton alloc] init];
    cover.backgroundColor = [UIColor blackColor];
    cover.frame = self.bounds;
    [cover addTarget:self action:@selector(backViewGesture) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cover];
    self.cover = cover;
    return _cover;
}


- (instancetype)initWithItems:(NSArray<NSString *> *)items
{
    if (!(self = [super init])) return nil;
    
    self.backgroundColor = [UIColor clearColor];
    self.items = items;

    _hideOnTouchOutside = YES; // 默认点击半透明层隐藏弹窗
    _contentAlignment = RQContentAlignmentCenter;

    return self;
}


// 整个tableView内容的高度
- (CGFloat)tableViewHeight {
    
    NSInteger count = (_items.count > 5) ? 6 : _items.count;
    CGFloat rowHeightSum = count * RQActionSheetRowHeight ;
    return rowHeightSum;
}

// 整体高度
- (CGFloat)contentHeight
{
    return [self tableViewHeight] + RQActionSheetRowHeight + RQActionSheetDefaultMargin *2 ;
}

// 点击确定按钮<多选情况>
- (void)clickBottomBtn
{
    if (_isMultiple) {
        
        [self hideWithCompletion:^{
            if (self.selectArray.count) {
                if (_multiplesDelectedHandler) {
                    _multiplesDelectedHandler(self.selectArray);
                }
            }
        }];
    
    
    }else{
        [self hideWithCompletion:nil];
    }
    
}

// 点击背景半透明遮罩层隐藏
- (void)backViewGesture
{
    if (_hideOnTouchOutside) {
        [self hideWithCompletion:nil];
    }
}

// 隐藏
- (void)hideWithCompletion:(void(^)())completion {
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.cover.alpha  = 0;
        CGFloat height = [self contentHeight];
        self.controllerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, height);
    
    } completion:^(BOOL finished) {

        if (completion) completion();
      
        [_controllerView removeFromSuperview];
        _controllerView = nil;
      
        [_tableView removeFromSuperview];
        _tableView = nil;
        [_bottomBtn removeFromSuperview];
        _bottomBtn = nil;
        
        [self removeFromSuperview];

        self.selectedHandler = nil;
    }];
}

#pragma mark - public
/*! @brief 单展示, 不绑定block回调 */
- (void)showWithMultipleSelectedCompletion:(RQActionSheetMultipleHandler)multiplesDelectedHandler; {

    self.multiplesDelectedHandler = multiplesDelectedHandler;
    [self setupUI];
}

- (void)showWithSelectedCompletion:(RQActionSheetHandler)selectedHandler {
    
    self.selectedHandler = selectedHandler;
    [self setupUI];
}

- (void)setupUI
{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.frame = window.bounds;
    [window addSubview:self];
    
    self.cover.alpha = 0.0;
    
    CGFloat tvHeight = [self tableViewHeight];
    
    if (_items.count > 5) {
        self.tableView.scrollEnabled = YES;
        self.tableView.showsVerticalScrollIndicator = YES;

    }
    CGFloat width = kScreenWidth - RQSActionSheetLeftRightMargin *2;
    self.tableView.frame = CGRectMake(RQSActionSheetLeftRightMargin, 0, width, tvHeight);
    CGFloat bottomY = tvHeight + RQActionSheetDefaultMargin;
    [self.controllerView addSubview:self.tableView];
    
    self.bottomBtn.frame = CGRectMake(RQSActionSheetLeftRightMargin, bottomY, width, RQActionSheetRowHeight);
    [self.controllerView addSubview:self.bottomBtn];
    
    CGFloat height = [self contentHeight];
    self.controllerView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, height);
    
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        if (_hideOnTouchOutside) {
            self.cover.alpha = 0.5;
        }
        self.controllerView.frame = CGRectMake(0, kScreenHeight - height, kScreenWidth, height);
        
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _items.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return RQActionSheetRowHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RQActionSheetCell *cell = [tableView dequeueReusableCellWithIdentifier:kRQActionSheetCellIdentifier];
    cell.textStr = _items[indexPath.row];
    cell.contentAlignment = self.contentAlignment;
    cell.isSelected = [self.selectArray containsObject:indexPath] ? YES: NO;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_isMultiple) {
        
        if ([self.selectArray containsObject:indexPath]) {
            [self.selectArray removeObject:indexPath];
        }else {
            [self.selectArray addObject:indexPath];
        }
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        
    }else{
        // 延迟0.1秒隐藏让用户既看到点击效果又不影响体验
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            __weak __typeof(&*self)weakSelf = self;
            [self hideWithCompletion:^{
                if (indexPath.section == 0) {
                    if (_selectedHandler) {
                        _selectedHandler(indexPath.row);
                    }
                    if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(actionSheet:selectedIndex:)]) {
                        [weakSelf.delegate actionSheet:self selectedIndex:indexPath.row];
                    }
                }
            }];
        });
    }

}


- (void)dealloc {
    
    NSLog(@"-- RQActionSheet did dealloc -- [%p] -- [%p] -- [%p]", _bottomBtn, _controllerView, _tableView);
}

@end
